/**
 * 对象池
 */

namespace CommonFrame {
    export class ObjectPool extends Singleton {
        private _pools = {};
        private _popedObj = {};

        createPool($clzName, $maxNum, ...param) {
            this._pools[$clzName] = [];
            this._popedObj[$clzName] = [];
            let clz = egret.getDefinitionByName($clzName);
            for (let i = 0; i < $maxNum; i++) {
                this._pools[$clzName].push(new clz(...param));
            }
        }
        getObject($clzName) {
            let pool = this._pools[$clzName];
            let popedObj: any[] = this._popedObj[$clzName];
            let obj;
            if (!pool) {
                Frame.debugConsole(this, `对象池${$clzName}不存在`);
                return;
            }
            if (pool.length != 0) {
                obj = pool.pop();
                popedObj.push(obj);
            }
            else {
                if (popedObj.length != 0) {
                    let recycleObj = popedObj.splice(1, 1)
                    pool.push(recycleObj);
                    return this.getObject($clzName);
                }
                Frame.debugConsole(this, `对象池中${$clzName}数量为0`);
                return;
            }

            return obj;
        }
    }
}